﻿import os
import requests
import re,time
from datetime import datetime
import time ,os,smtplib
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime
os.system("rm -rf logs/*")
import sys

# 设置间隔时间（秒）
interval = 10  # 600秒 = 10分钟
def send_msg(msg,msg_type,file_name):
    try:
        smtp = smtplib.SMTP_SSL("smtp.qq.com")
        smtp.connect("smtp.qq.com", port=465)

        # 登录，需要：登录邮箱和授权码
        smtp.login(user="【qq邮箱】", password="【授权码】")

        message = MIMEMultipart()
        message['From'] = Header("【昵称】 <【qq邮箱】>")  # 发件人的昵称
        message['To'] = Header("安安", 'utf-8')  # 收件人的昵称
        message['Subject'] = Header(msg_type, 'utf-8').encode()  # 定义主题内容
        #msg_sub=MIMEText(msg,_charset="utf-8")
        #message.attach(msg_sub)
        fp = open(file_name, 'rb')
        # 创建MIMEApplication对象并添加到邮件对象中
        mime = MIMEText(fp.read(),_charset="utf-8")#Application(fp.read(), 'text')
        #mime.add_header('Content-Disposition', 'attachment', filename=file_name)
        message.attach(mime)
        fp.close()
        smtp.sendmail(from_addr="【qq邮箱】", to_addrs=["【qq邮箱】"], msg=message.as_string())
        smtp.quit()
        return True
    except:
        return False
# 获取当前日期和时间
now = datetime.now()
 
# 分别获取年、月、日、时、分、秒
year = str(now.year)
month = str(now.month)
day = str(now.day)
hour = str(now.hour)
minute = str(now.minute)
second = str(now.second)
url_send_data = 'http://【IP:PORT】/send_data2'
c_data_dir="c_data"
test_c_data=sys.argv[1]
# 使用os.listdir来列出目录下的所有内容
entries = os.listdir(c_data_dir)
headers = {
    'Content-Type': 'application/json'
}
# 过滤出所有子目录
subdirectories = [d for d in entries if os.path.isdir(os.path.join(c_data_dir, d))]
log_num=0
url_get_processed_data = 'http://【IP:PORT】/get_processed_data2'
#清空已有数据
response = requests.post(url_get_processed_data, headers=headers)
res_list=[]
res_list_v=[]
with open(test_c_data, 'r', encoding='utf-8') as file:
    # 读取文件内容
    data_check = file.read()
for subdirectory1 in subdirectories:
    wrong_path=os.path.join(c_data_dir, subdirectory1)
    entries = os.listdir(wrong_path)
    subdirectories2 = [d for d in entries if os.path.isdir(os.path.join(wrong_path, d))]
    for subdirectory2 in subdirectories2:

        wrong_path2=os.path.join(wrong_path,subdirectory2)
        entries = os.listdir(wrong_path2)
        subdirectories3 = [d for d in entries if os.path.isdir(os.path.join(wrong_path2, d))]
        for subdirectory3 in subdirectories3:
            print(subdirectory1,subdirectory2,subdirectory3)
            while(True):
                try:
                    time.sleep(2)
                    wrong_path_data=os.path.join(wrong_path2,subdirectory3)
                    data1=os.path.join(wrong_path_data,"wrong.c")
                    data2=os.path.join(wrong_path_data,"right.c")
                    with open(data1, 'r', encoding='utf-8') as file:
                        # 读取文件内容
                        content1 = file.read()
                    with open(data2, 'r', encoding='utf-8') as file:
                        # 读取文件内容
                        content2 = file.read()

                    prompt_in="请你用一段话告诉我错误的不规范的C语言代码一和正确的规范C语言代码二的方式的区别，不要告诉我代码：代码一：\n"+content1+"代码二：\n"+content2
                    data_to_send = {'data': prompt_in}
                    for i in range(60):
                        time.sleep(1)
                        try:
                            response = requests.post(url_send_data, json=data_to_send, headers=headers)
                        except:
                            print("time error1!")
                            raise ValueError("-1")

                        break
                    else:
                        raise ValueError("-1")
                    # 等待PC2处理数据
                    # PC1从服务器获取处理后的数据
                    url_get_processed_data = 'http://【IP:PORT】/get_processed_data2'
                    for i in range(60):
                        time.sleep(1)
                        try:
                            response = requests.post(url_get_processed_data, headers=headers)
                        except:
                            print("time error2!")
                            raise ValueError("-1")
                        if response.json()['status']=='no data':
                            continue
                        result=response.json()['processed_data']
                        break
                    else:
                        raise ValueError("-1")

                    prompt_in="你必须好好看清我说的内容,我给你的代码二对代码一的不安全进行了修复,修复规则是这样的："+result+"\n，请你对可能需要修改的C语言代码三进行分析,如果你认定代码三在基于代码一向代码二转变的规则下为不安全并且需要修改的话告诉我为什么要修改,告诉我你认为可能需要修改的地方在哪,优先认为不需要修改。代码一，代码二以及需要修改的代码三分别是:\n代码一：\n"+content1+"\n代码二：\n"+content2+"\n代码三:\n"+data_check+"\n不要跟我说代码"
                    data_to_send = {'data': prompt_in}
                    for i in range(60):
                        time.sleep(1)
                        try:
                            response = requests.post(url_send_data, json=data_to_send, headers=headers)
                        except:
                            print("time error3!")
                            raise ValueError("-1")
                        break
                    else:
                        raise ValueError("-1")
                    with open(os.path.join("logs",subdirectory1+"-1-"+subdirectory2+"-"+subdirectory3+"-"+str(log_num)+".log"), 'w', encoding='utf-8') as file:
                        # 读取文件内容
                        file.write(str(result))
                    # 等待PC2处理数据
                    # PC1从服务器获取处理后的数据
                    url_get_processed_data = 'http://【IP:PORT】/get_processed_data2'
                    for i in range(60):
                        time.sleep(1)
                        try:
                            response = requests.post(url_get_processed_data, headers=headers)
                        except:
                            print("time error4!")
                            raise ValueError("-1")
                        if response.json()['status']=='no data':
                            continue
                        result=response.json()['processed_data']
                        break
                    else:
                        raise ValueError("-1")
                    with open(os.path.join("logs",subdirectory1+"-"+subdirectory2+"-"+subdirectory3+"-"+str(log_num)+".log"), 'w', encoding='utf-8') as file:
                        # 读取文件内容
                        file.write(str(result))
                except:
                    print("error!")
                    try:
                        response = requests.post(url_get_processed_data, headers=headers)
                    except:
                        pass    
                break
            log_num+=1
if True:
    res_list=[]
    res_list_v=[]
    res_list_r=[]
    log_d="logs"
    subdirectories = os.listdir(log_d)
    for subd in subdirectories:
        if len(subd.split("-"))==6:
            continue
        with open(os.path.join(log_d,subd), 'r', encoding='utf-8') as file:
            # 读取文件内容
            result=file.read()
        res_list_v.append([subd.split("-")[0],subd.split("-")[1]+"-"+subd.split("-")[2],subd.split("-")[3]])
        res_list_r.append(subd)
data_check_list=data_check.split("\n")
log_txt=''
log_txt=log_txt+"+++++++++++++++++++++++++++\n"
log_txt=log_txt+"Acautoai-Safety-Tools检测报告\n"
log_txt=log_txt+"文件名:"+test_c_data+" 启动时间:"+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+"\n"
log_txt=log_txt+"+++++++++++++++++++++++++++\n"
for i in range(len(data_check_list)):
    log_txt=log_txt+str(i)+" "+data_check_list[i]+"\n"
for res_i in range(len(res_list_v)):
    log_txt=log_txt+"===========================\n"
    log_txt=log_txt+"不安全类型:"+res_list_v[res_i][1]+res_list_v[res_i][2]+"\n"
    menu_text_p=os.path.join("logs",res_list_r[res_i])

    
    with open(menu_text_p, 'r', encoding='utf-8') as file:
        # 读取文件内容
        content = file.read()
    
    log_txt=log_txt+"===========================\n"
    log_txt=log_txt+"===========================\n"
    log_txt=log_txt+"分析结果：\n"
    log_txt=log_txt+content+"\n"
    #log_txt=log_txt+"不安全代码：\n"
    #log_txt=log_txt+content1+"\n"
    #log_txt=log_txt+"安全代码：\n"
    #log_txt=log_txt+content2+"\n"
    log_txt=log_txt+"===========================\n"


log_txt=log_txt+"+++++++++++++++++++++++++++\n"
log_txt=log_txt+"欢迎关注公众号：b584565617\n"
log_txt=log_txt+"+++++++++++++++++++++++++++\n"
with open("res_log.txt", 'w', encoding='utf-8') as file:
    # 读取文件内容
    file.write(str(log_txt))
send_msg("完成提醒","[Acautoai提醒]!!!!","res_log.txt")
#send_msg("完成提醒","[Acautoai提醒]!!!!",test_c_data)
print("success!")
